package main

import (
	"flag"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"unicode/utf8"

	"gitverse.ru/panarinv/tmplter"
)

func main() {

	comma := flag.String("d", "\t", "field delimiter for collections")
	flag.Parse()
	comma_rune, _ := utf8.DecodeRuneInString(*comma)

	stdinstat, _ := os.Stdin.Stat()
	if len(os.Args) == 1 && stdinstat.Mode()&os.ModeCharDevice > 0 {
		fmt.Fprintf(
			os.Stderr,
			"Usage: %v [OPTIONS] [CSV_files...] <template >result 2>errors\n"+
				"Options:\n",
			filepath.Base(os.Args[0]))
		flag.PrintDefaults()
		fmt.Fprintf(
			os.Stderr,
			"Template: ...{{file.csv/}}...{{field_1}}...{{/file.csv}}...\n"+
				"file.csv:\n"+
				"  field_1,field_2,...\n"+
				"  value11,value12,...\n"+
				"  value21,value22,...\n"+
				"  ...\n")
		os.Exit(3)
	}

	clcs := map[string][]map[string]string{}

	for _, arg := range flag.Args() {
		filename := arg

		// Read collection from CSV file
		file_bytes, err := os.ReadFile(filename)
		if err != nil {
			panic(err.Error())
		}
		file_content := string(file_bytes)

		clc_items, err := tmplter.ReadCollection(file_content, comma_rune)
		if err != nil {
			panic(err.Error())
		}
		clc_title := filepath.Base(filename)
		clcs[clc_title] = clc_items
	}

	template_bytes, _ := io.ReadAll(os.Stdin)
	template := string(template_bytes)

	result, err := tmplter.ParseTemplate(template, clcs, map[string]string{})
	if err != nil {
		os.Stderr.WriteString(err.Error() + "\n")
		os.Exit(2)
	}

	os.Stdout.WriteString(result)

}
